<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { changeAdminPassword } from "@/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const formObj = reactive({
  password: "",
  checkpwd: "",
});
const formRef = ref<FormInstance>();
const rules = reactive({
  password: [{ required: true, message: "账号密码不能为空", trigger: "blur" }],
  checkpwd: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    { validator: checkpwdFun, trigger: "blur" },
  ],
});
function checkpwdFun(_rule: any, value: any, callback: any) {
  if (value != formObj.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
}
async function submitForm() {
  await formRef.value?.validate(async (valid, _fields) => {
    if (valid) {
      const res = await changeAdminPassword({ password: formObj.password });
      if (res.data.errno == 0) {
        ElMessage.success(res.data.errmsg + "，请重新登录");
        router.push("/login");
      } else {
        ElMessage.error(res.data.errmsg);
      }
    }
  });
}
function resetForm() {
  formObj.password = "";
  formObj.checkpwd = "";
}
</script>

<template>
  <section class="person_info">
    <div>个人信息</div>
    <div>
      <el-form
        ref="formRef"
        :model="formObj"
        :rules="rules"
        label-width="200"
        status-icon
      >
        <el-form-item label="修改密码" prop="password">
          <el-input
            v-model="formObj.password"
            style="width: 90%"
            placeholder="请填写账号密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="请再次输入密码" prop="checkpwd">
          <el-input
            v-model="formObj.checkpwd"
            style="width: 90%"
            placeholder="请填写确认密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </section>
</template>

<style scoped>
.person_info {
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  width: 70%;
  box-shadow: 0px 0px 5px 5px #e4e7ed;
  margin: 20px 20px 20px 0px;
}
.person_info > div:nth-child(1) {
  font-size: 15px;
  text-indent: 15px;
  line-height: 50px;
  border-bottom: 1px solid #e4e7ed;
}
.person_info > div:nth-child(2) {
  margin-top: 30px;
}
</style>
